/**
 * 主JS文件 - 包含通用功能和工具函数
 */

// API基础URL
const API_BASE_URL = '/api/v1';

// API端点
const API_ENDPOINTS = {
    STATS: `${API_BASE_URL}/stats`,
    HOT_TOPICS: `${API_BASE_URL}/topics/hot`,
    LATEST_NEWS: `${API_BASE_URL}/news/latest`,
    POPULAR_PAPERS: `${API_BASE_URL}/papers/popular`,
    COMPANY_ACTIVITY: `${API_BASE_URL}/companies/activity`,
    SEARCH: `${API_BASE_URL}/search`,
    COMPANY_DETAIL: `${API_BASE_URL}/companies`
};

/**
 * 通用API调用函数
 * @param {string} url - API端点URL
 * @param {Object} options - 请求选项
 * @returns {Promise} - 返回Promise对象
 */
async function fetchAPI(url, options = {}) {
    try {
        const response = await fetch(url, {
            ...options,
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            }
        });

        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status}`);
        }

        return await response.json();
    } catch (error) {
        console.error('API请求错误:', error);
        throw error;
    }
}

/**
 * 格式化日期
 * @param {string} dateString - 日期字符串
 * @returns {string} - 格式化后的日期字符串
 */
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}

/**
 * 数字格式化，大数字显示为K或M单位
 * @param {number} num - 要格式化的数字
 * @returns {string} - 格式化后的字符串
 */
function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
}

/**
 * 计算百分比变化
 * @param {number} current - 当前值
 * @param {number} previous - 之前的值
 * @returns {string} - 格式化的百分比字符串
 */
function calculatePercentChange(current, previous) {
    if (previous === 0) return '+100%';
    
    const change = ((current - previous) / previous) * 100;
    return (change > 0 ? '+' : '') + change.toFixed(1) + '%';
}

/**
 * 创建HTML元素
 * @param {string} tag - 标签名
 * @param {Object} attributes - 属性对象
 * @param {string|Node} content - 内容
 * @returns {HTMLElement} - 创建的元素
 */
function createElement(tag, attributes = {}, content = '') {
    const element = document.createElement(tag);
    
    Object.entries(attributes).forEach(([key, value]) => {
        if (key === 'classList' && Array.isArray(value)) {
            value.forEach(cls => element.classList.add(cls));
        } else {
            element.setAttribute(key, value);
        }
    });
    
    if (typeof content === 'string') {
        element.innerHTML = content;
    } else if (content instanceof Node) {
        element.appendChild(content);
    }
    
    return element;
}

/**
 * 显示加载中指示器
 * @param {HTMLElement} container - 容器元素
 */
function showLoading(container) {
    container.innerHTML = `
        <div class="loading-spinner">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
        </div>
    `;
}

/**
 * 显示错误消息
 * @param {HTMLElement} container - 容器元素
 * @param {string} message - 错误消息
 */
function showError(container, message = '加载数据失败，请稍后再试。') {
    container.innerHTML = `
        <div class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i>
            ${message}
        </div>
    `;
}

/**
 * 防抖函数
 * @param {Function} func - 要执行的函数
 * @param {number} wait - 等待时间（毫秒）
 * @returns {Function} - 防抖处理后的函数
 */
function debounce(func, wait = 300) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

/**
 * 获取URL参数
 * @param {string} name - 参数名
 * @returns {string|null} - 参数值
 */
function getUrlParameter(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

/**
 * 初始化导航条激活状态
 */
function initNavActive() {
    const currentPath = window.location.pathname;
    const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
    
    navLinks.forEach(link => {
        const href = link.getAttribute('href');
        if (href === currentPath || 
            (href !== '/' && currentPath.startsWith(href))) {
            link.classList.add('active');
        }
    });
}

// 页面加载时初始化导航
document.addEventListener('DOMContentLoaded', () => {
    initNavActive();
});

// 导出公共函数
window.App = {
    API_ENDPOINTS,
    fetchAPI,
    formatDate,
    formatNumber,
    calculatePercentChange,
    createElement,
    showLoading,
    showError,
    debounce,
    getUrlParameter
}; 